<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试API - API文档管理系统</title>
    <link th:href="@{/css/bootstrap/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/css/bootstrap/font/bootstrap-icons.css}" rel="stylesheet">
    <link th:href="@{/css/style.css}" rel="stylesheet">
    <style>
        .response-container {
            max-height: 400px;
            overflow-y: auto;
        }
        .status-container {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            padding: 1rem;
        }
        .data-container {
            background-color: #2d2d2d;
            color: #ffffff;
            border-radius: 0.375rem;
            padding: 1rem;
            font-family: 'Courier New', monospace;
            white-space: pre-wrap;
            min-height: 200px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <!-- 导航栏 -->
        <nav class="navbar navbar-expand-lg navbar-dark bg-primary mb-4">
            <div class="container-fluid">
                <a class="navbar-brand" th:href="@{/api-doc/}">
                    <i class="bi bi-book"></i>
                    API文档管理系统
                </a>
                <div class="navbar-nav ms-auto">
                    <a class="nav-link" th:href="@{/api-doc/}">
                        <i class="bi bi-house"></i>
                        首页
                    </a>
                    <a class="nav-link" th:href="@{/api-doc/list}">
                        <i class="bi bi-list"></i>
                        API列表
                    </a>
                    <a class="nav-link" th:href="@{/api-doc/app-service/list}">
                        <i class="bi bi-server"></i>
                        应用服务
                    </a>
                    <a class="nav-link" th:href="@{/api-doc/create}">
                        <i class="bi bi-plus-circle"></i>
                        新增API
                    </a>
                    <a class="nav-link" th:href="@{/swagger-ui/index.html}" target="_blank">
                        <i class="bi bi-code-square"></i>
                        Swagger UI
                    </a>
                </div>
            </div>
        </nav>

        <!-- 面包屑导航 -->
        <nav aria-label="breadcrumb" class="mb-4">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a th:href="@{/api-doc/}">首页</a></li>
                <li class="breadcrumb-item"><a th:href="@{/api-doc/list}">API列表</a></li>
                <li class="breadcrumb-item"><a th:href="@{/api-doc/detail/{id}(id=${api.id})}" th:text="${api.name}">API详情</a></li>
                <li class="breadcrumb-item active" aria-current="page">测试API</li>
            </ol>
        </nav>

        <!-- 错误信息显示 -->
        <div th:if="${error}" class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="bi bi-exclamation-triangle"></i>
            <span th:text="${error}"></span>
            <button type="button" class="btn-close" data-dismiss="alert" aria-label="Close"></button>
        </div>

        <!-- API测试 -->
        <div class="row justify-content-center">
            <div class="col-lg-10">
                <div class="card">
                    <div class="card-header">
                        <div class="row align-items-center">
                            <div class="col-md-6">
                                <h5 class="card-title mb-0">
                                    <i class="bi bi-lightning"></i>
                                    测试API
                                </h5>
                            </div>
                            <div class="col-md-6 text-end">
                                <a th:href="@{/api-doc/detail/{id}(id=${api.id})}" class="btn btn-secondary">
                                    <i class="bi bi-arrow-left"></i>
                                    返回详情
                                </a>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <!-- API基本信息 -->
                        <div class="row mb-4">
                            <div class="col-md-12">
                                <h6>
                                    <span th:class="'badge bg-' + ${api.method == 'GET' ? 'success' : (api.method == 'POST' ? 'primary' : (api.method == 'PUT' ? 'warning' : (api.method == 'DELETE' ? 'danger' : 'secondary')))}" 
                                          th:text="${api.method}">
                                        GET
                                    </span>
                                    <span th:text="${api.name}" class="ms-2">API名称</span>
                                </h6>
                                <p class="text-muted" th:text="${api.path}">/api/v1/example</p>
                                <p th:text="${api.description}">API描述信息</p>
                            </div>
                        </div>

                        <!-- 关联应用服务信息 -->
                        <div class="mb-4" th:if="${appService}">
                            <h6 class="border-bottom pb-2">
                                <i class="bi bi-server"></i>
                                关联应用服务
                            </h6>
                            <div class="card">
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <p><strong>服务名称:</strong> <span th:text="${appService.name}">服务名称</span></p>
                                            <p><strong>协议:</strong> <span th:text="${appService.protocol}">协议</span></p>
                                            <p><strong>IP地址:</strong> <span th:text="${appService.ipAddress}">IP地址</span></p>
                                        </div>
                                        <div class="col-md-6">
                                            <p><strong>端口:</strong> <span th:text="${appService.port}">端口</span></p>
                                            <p><strong>上下文路径:</strong> <span th:text="${appService.contextPath}">上下文路径</span></p>
                                            <p><strong>完整基础URL:</strong> <span th:text="${appService.baseUrl}">完整URL</span></p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 完整API地址与请求方式 -->
                        <div class="mb-4">
                            <h6 class="border-bottom pb-2">
                                <i class="bi bi-link"></i>
                                完整API地址与请求方式
                            </h6>
                            <div class="card">
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-12">
                                            <p><strong>请求方法:</strong> 
                                                <span th:class="'badge bg-' + ${api.method == 'GET' ? 'success' : (api.method == 'POST' ? 'primary' : (api.method == 'PUT' ? 'warning' : (api.method == 'DELETE' ? 'danger' : 'secondary')))}" 
                                                      th:text="${api.method}">
                                                    GET
                                                </span>
                                            </p>
                                            <p><strong>完整API地址:</strong> 
                                                <span id="fullApiUrl" class="text-primary"></span>
                                                <button type="button" class="btn btn-outline-primary btn-sm ms-2" onclick="copyToClipboard()">
                                                    <i class="bi bi-clipboard"></i> 复制
                                                </button>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 测试表单 -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h6 class="card-title mb-0">
                                    <i class="bi bi-sliders"></i>
                                    测试参数
                                </h6>
                            </div>
                            <div class="card-body">
                                <form id="testForm">
                                    <!-- Params区域 - 地址栏传参数 -->
                                    <div class="mb-3">
                                        <label class="form-label">
                                            <i class="bi bi-link"></i>
                                            Query Parameters (地址栏参数)
                                        </label>
                                        <div id="queryParamsContainer">
                                            <div class="row mb-2 queryParamsRow">
                                                <div class="col-md-5">
                                                    <input type="text" class="form-control" placeholder="参数名" name="paramKey[]">
                                                </div>
                                                <div class="col-md-5">
                                                    <input type="text" class="form-control" placeholder="参数值" name="paramValue[]">
                                                </div>
                                                <div class="col-md-2">
                                                    <button type="button" class="btn btn-outline-danger" onclick="removeParamRow(this)">
                                                        <i class="bi bi-trash"></i>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="addParamRow()">
                                            <i class="bi bi-plus"></i> 添加参数
                                        </button>
                                        <div class="form-text">添加URL查询参数，例如 ?key1=value1&key2=value2</div>
                                    </div>

                                    <!-- Headers区域 - 请求头 -->
                                    <div class="mb-3">
                                        <label class="form-label">
                                            <i class="bi bi-tag"></i>
                                            Headers (请求头)
                                        </label>
                                        <div id="headersContainer">
                                            <div class="row mb-2 headersRow">
                                                <div class="col-md-5">
                                                    <input type="text" class="form-control" placeholder="Header名" name="headerKey[]" value="Content-Type">
                                                </div>
                                                <div class="col-md-5">
                                                    <select class="form-control" name="headerValue[]">
                                                        <option value="application/json">application/json</option>
                                                        <option value="application/x-www-form-urlencoded">application/x-www-form-urlencoded</option>
                                                        <option value="text/plain">text/plain</option>
                                                        <option value="application/xml">application/xml</option>
                                                        <option value="text/html">text/html</option>
                                                    </select>
                                                </div>
                                                <div class="col-md-2">
                                                    <button type="button" class="btn btn-outline-danger" onclick="removeHeaderRow(this)">
                                                        <i class="bi bi-trash"></i>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="addHeaderRow()">
                                            <i class="bi bi-plus"></i> 添加Header
                                        </button>
                                        <div class="form-text">添加请求头信息</div>
                                    </div>

                                    <!-- Body区域 - 请求体 -->
                                    <div class="mb-3">
                                        <label class="form-label">
                                            <i class="bi bi-file-text"></i>
                                            Body (请求体)
                                        </label>
                                        <ul class="nav nav-tabs" id="bodyTab" role="tablist">
                                            <li class="nav-item" role="presentation">
                                                <button class="nav-link active" id="form-data-tab" data-toggle="tab" data-target="#form-data" type="button" role="tab">
                                                    Form Data
                                                </button>
                                            </li>
                                            <li class="nav-item" role="presentation">
                                                <button class="nav-link" id="raw-tab" data-toggle="tab" data-target="#raw" type="button" role="tab">
                                                    Raw (JSON)
                                                </button>
                                            </li>
                                        </ul>
                                        <div class="tab-content" id="bodyTabContent">
                                            <!-- Form Data -->
                                            <div class="tab-pane fade show active" id="form-data" role="tabpanel">
                                                <div class="mt-3" id="formDataContainer">
                                                    <div class="row mb-2 formDataRow">
                                                        <div class="col-md-5">
                                                            <input type="text" class="form-control" placeholder="字段名" name="formKey[]">
                                                        </div>
                                                        <div class="col-md-5">
                                                            <input type="text" class="form-control" placeholder="字段值" name="formValue[]">
                                                        </div>
                                                        <div class="col-md-2">
                                                            <button type="button" class="btn btn-outline-danger" onclick="removeFormRow(this)">
                                                                <i class="bi bi-trash"></i>
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="addFormRow()">
                                                    <i class="bi bi-plus"></i> 添加字段
                                                </button>
                                            </div>
                                            <!-- Raw (JSON) -->
                                            <div class="tab-pane fade" id="raw" role="tabpanel">
                                                <div class="mt-3">
                                                    <textarea class="form-control" id="rawBody" rows="6" placeholder='{"key": "value"}'></textarea>
                                                    <div class="form-text">输入JSON格式的数据</div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="d-grid">
                                        <button type="button" class="btn btn-primary" th:onclick="'testApi('+${api.id}+')'">
                                            <i class="bi bi-lightning"></i>
                                            执行测试
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <!-- 测试结果 -->
                        <div class="card">
                            <div class="card-header">
                                <h6 class="card-title mb-0">
                                    <i class="bi bi-terminal"></i>
                                    测试结果
                                </h6>
                            </div>
                            <div class="card-body">
                                <!-- 状态信息 -->
                                <div class="mb-3">
                                    <h6 class="border-bottom pb-2">
                                        <i class="bi bi-info-circle"></i>
                                        请求状态
                                    </h6>
                                    <div class="status-container">
                                        <div id="statusResult">等待执行测试...</div>
                                    </div>
                                </div>
                                
                                <!-- 响应数据 -->
                                <div>
                                    <h6 class="border-bottom pb-2">
                                        <i class="bi bi-file-earmark-text"></i>
                                        响应数据
                                    </h6>
                                    <div class="response-container">
                                        <div id="dataResult" class="data-container">执行测试后，响应数据将显示在这里...</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 操作按钮 -->
                <div class="d-grid gap-2 d-md-flex justify-content-md-end mt-3">
                    <a th:href="@{/api-doc/detail/{id}(id=${api.id})}" class="btn btn-secondary">
                        <i class="bi bi-arrow-left"></i>
                        返回详情
                    </a>
                </div>
            </div>
        </div>
    </div>

    <script th:src="@{/js/jquery-3.6.0.min.js}"></script>
    <script th:src="@{/js/bootstrap/bootstrap.bundle.min.js}"></script>
    <script th:inline="javascript">
        // 添加参数行
        function addParamRow() {
            const container = $('#queryParamsContainer');
            const newRow = $(`
                <div class="row mb-2 queryParamsRow">
                    <div class="col-md-5">
                        <input type="text" class="form-control" placeholder="参数名" name="paramKey[]">
                    </div>
                    <div class="col-md-5">
                        <input type="text" class="form-control" placeholder="参数值" name="paramValue[]">
                    </div>
                    <div class="col-md-2">
                        <button type="button" class="btn btn-outline-danger" onclick="removeParamRow(this)">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                </div>
            `);
            container.append(newRow);
        }

        // 删除参数行
        function removeParamRow(button) {
            $(button).closest('.queryParamsRow').remove();
        }

        // 添加Header行
        function addHeaderRow() {
            const container = $('#headersContainer');
            const newRow = $(`
                <div class="row mb-2 headersRow">
                    <div class="col-md-5">
                        <input type="text" class="form-control" placeholder="Header名" name="headerKey[]">
                    </div>
                    <div class="col-md-5">
                        <select class="form-control" name="headerValue[]">
                            <option value="application/json">application/json</option>
                            <option value="application/x-www-form-urlencoded">application/x-www-form-urlencoded</option>
                            <option value="text/plain">text/plain</option>
                            <option value="application/xml">application/xml</option>
                            <option value="text/html">text/html</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button type="button" class="btn btn-outline-danger" onclick="removeHeaderRow(this)">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                </div>
            `);
            container.append(newRow);
        }

        // 删除Header行
        function removeHeaderRow(button) {
            $(button).closest('.headersRow').remove();
        }

        // 添加Form行
        function addFormRow() {
            const container = $('#formDataContainer');
            const newRow = $(`
                <div class="row mb-2 formDataRow">
                    <div class="col-md-5">
                        <input type="text" class="form-control" placeholder="字段名" name="formKey[]">
                    </div>
                    <div class="col-md-5">
                        <input type="text" class="form-control" placeholder="字段值" name="formValue[]">
                    </div>
                    <div class="col-md-2">
                        <button type="button" class="btn btn-outline-danger" onclick="removeFormRow(this)">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                </div>
            `);
            container.append(newRow);
        }

        // 删除Form行
        function removeFormRow(button) {
            $(button).closest('.formDataRow').remove();
        }

        // 构建完整URL
        function buildFullUrl(apiPath, appService) {
            let baseUrl = '';
            if (appService) {
                // 使用应用服务的完整URL
                baseUrl = appService.protocol + '://' + appService.ipAddress + ':' + appService.port + appService.contextPath;
            } else {
                // 默认URL
                baseUrl = 'http://localhost:8080';
            }
            
            // 确保基础URL不以斜杠结尾
            if (baseUrl.endsWith('/')) {
                baseUrl = baseUrl.slice(0, -1);
            }
            
            // 确保API路径以斜杠开头
            if (!apiPath.startsWith('/')) {
                apiPath = '/' + apiPath;
            }
            
            return baseUrl + apiPath;
        }

        // 获取查询参数
        function getQueryParams() {
            const paramKeys = $('input[name="paramKey[]"]');
            const paramValues = $('input[name="paramValue[]"]');
            const params = [];
            
            for (let i = 0; i < paramKeys.length; i++) {
                const key = $(paramKeys[i]).val().trim();
                const value = $(paramValues[i]).val().trim();
                if (key && value) {
                    params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
                }
            }
            
            return params.length > 0 ? '?' + params.join('&') : '';
        }

        // 获取Headers
        function getHeaders() {
            const headerKeys = $('input[name="headerKey[]"]');
            const headerValues = $('select[name="headerValue[]"]');
            const headers = {};
            
            for (let i = 0; i < headerKeys.length; i++) {
                const key = $(headerKeys[i]).val().trim();
                const value = $(headerValues[i]).val().trim();
                if (key && value) {
                    headers[key] = value;
                }
            }
            
            return headers;
        }

        // 获取Body数据
        function getBodyData() {
            // 检查当前激活的tab
            const activeTab = $('.tab-pane.active').attr('id');
            
            if (activeTab === 'form-data') {
                // Form Data - 返回null，让后端处理
                return null;
            } else {
                // Raw (JSON)
                return $('#rawBody').val().trim();
            }
        }

        // 获取表单数据（用于FormData）
        function getFormData() {
            // 检查当前激活的tab
            const activeTab = $('.tab-pane.active').attr('id');
            
            if (activeTab === 'form-data') {
                // Form Data
                const formKeys = $('input[name="formKey[]"]');
                const formValues = $('input[name="formValue[]"]');
                const formDataObj = {};
                
                for (let i = 0; i < formKeys.length; i++) {
                    const key = $(formKeys[i]).val().trim();
                    const value = $(formValues[i]).val().trim();
                    if (key && value) {
                        formDataObj[key] = value;
                    }
                }
                
                return formDataObj;
            } else {
                // Raw (JSON) - 返回null
                return null;
            }
        }

        // 复制到剪贴板
        function copyToClipboard() {
            const fullUrl = $('#fullApiUrl').text();
            navigator.clipboard.writeText(fullUrl).then(() => {
                alert('已复制到剪贴板: ' + fullUrl);
            }).catch(err => {
                console.error('复制失败: ', err);
                // 降级方案
                const textArea = document.createElement('textarea');
                textArea.value = fullUrl;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                alert('已复制到剪贴板: ' + fullUrl);
            });
        }

        function testApi(id) {
            // 显示正在测试的提示
            $('#statusResult').text('正在测试API...');
            $('#dataResult').text('正在获取响应数据...');
            
            // 获取API信息（从Thymeleaf模板中获取）
            const apiPath = /*[[${api.path}]]*/ '';
            const apiMethod = /*[[${api.method}]]*/ 'GET';
            const appService = /*[[${appService}]]*/ null;
            
            // 构建完整URL
            const baseUrl = buildFullUrl(apiPath, appService);
            
            // 添加查询参数
            const queryParams = getQueryParams();
            const fullUrl = baseUrl + queryParams;
            
            // 显示完整API地址
            $('#fullApiUrl').text(fullUrl);
            
            // 获取Headers
            const headers = getHeaders();
            
            // 获取Body数据
            const bodyData = getBodyData();
            
            // 获取表单数据
            const formData = getFormData();
            
            // 构建请求数据
            const requestData = {
                url: fullUrl,
                method: apiMethod,  // 使用API的原始方法
                headers: headers,
                body: bodyData,
                formData: formData,
                isFormData: $('.tab-pane.active').attr('id') === 'form-data'
            };
            
            console.log('发送测试请求:', requestData);
            
            // 发送测试请求
            fetch('/api-doc/test-advanced/' + id, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            })
            .then(response => {
                // 显示状态信息
                $('#statusResult').html(`
                    <strong>状态码:</strong> ${response.status}<br>
                    <strong>状态文本:</strong> ${response.statusText}<br>
                    <strong>请求时间:</strong> ${new Date().toLocaleString()}
                `);
                return response.text();
            })
            .then(data => {
                // 显示响应数据
                $('#dataResult').text(data);
            })
            .catch(error => {
                console.error('Error:', error);
                $('#statusResult').html(`
                    <strong>错误:</strong> ${error.message}<br>
                    <strong>请求时间:</strong> ${new Date().toLocaleString()}
                `);
                $('#dataResult').text('测试失败: ' + error.message);
            });
        }
        
        // 页面加载完成后初始化
        $(document).ready(function() {
            // 获取API信息（从Thymeleaf模板中获取）
            const apiPath = /*[[${api.path}]]*/ '';
            const appService = /*[[${appService}]]*/ null;
            
            // 构建完整URL
            const baseUrl = buildFullUrl(apiPath, appService);
            const fullUrl = baseUrl; // 不添加查询参数
            
            // 显示完整API地址
            $('#fullApiUrl').text(fullUrl);
        });
    </script>
</body>
</html>